package com.lkd.job;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lkd.entity.AbstractEntity;
import com.lkd.entity.OrderCollectEntity;
import com.lkd.entity.OrderEntity;
import com.lkd.feignService.UserService;
import com.lkd.http.viewModel.OrderResp;
import com.lkd.service.OrderCollectService;
import com.lkd.service.OrderService;
import com.lkd.viewmodel.PartnerViewModel;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.ParameterizedType;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class CollectJob {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderCollectService orderCollectService;
    @Autowired
    private UserService userService;
    @XxlJob("CollectJobHandler")
    public ReturnT<String> workCountInitJobHandler(String param){
        List<OrderEntity> orderEntities = orderService.list(Wrappers.<OrderEntity>lambdaQuery()
                .ge(AbstractEntity::getCreateTime, LocalDate.now())
                .le(AbstractEntity::getCreateTime, LocalDate.now().plusDays(1)));
        //生成一个合作商对应的他所有订单map
        Map<Long, List<OrderEntity>> listMap = orderEntities.stream().collect(Collectors.groupingBy(OrderEntity::getNodeId));

        List<OrderCollectEntity> collectEntities = listMap.entrySet().stream().map(e -> {
            OrderCollectEntity orderCollectEntity = new OrderCollectEntity();
            int orderTotalMoney = 0;
            int totalBill = 0;
            for (OrderEntity orderEntity : e.getValue()) {
                PartnerViewModel partner = userService.getPartner(orderEntity.getOwnerId());
                orderCollectEntity.setRatio(partner.getRatio());
                orderTotalMoney = orderEntity.getPrice() + orderTotalMoney;
                totalBill = orderEntity.getBill() + totalBill;
                orderCollectEntity.setNodeId(orderEntity.getNodeId());
                orderCollectEntity.setNodeName(orderEntity.getNodeName());
            }
            orderCollectEntity.setDate(LocalDate.now());
            orderCollectEntity.setTotalBill(totalBill);
            orderCollectEntity.setOrderCount(e.getValue().size());
            orderCollectEntity.setOrderTotalMoney(orderTotalMoney);
            return orderCollectEntity;
        }).collect(Collectors.toList());
    if (orderCollectService.saveBatch(collectEntities)){
        return ReturnT.SUCCESS;
    }else {
        return ReturnT.FAIL;
    }
    }
}
